#include "mt.h"
#include <stdio.h>

static unsigned int MT[624];
static int index = 0;

void mt_seed(unsigned int seed)
{
	int i;
	MT[0] = seed;
	for (i=1; i<624; ++i) {
		MT[i] = 1812433253U * (MT[i-1] ^ (MT[i-1]>>30)) + i;
	}
}

static void generateNumbers() {
	int i;
	for (i=0; i<624; ++i) {
		unsigned int y = (MT[i] & 0x1) + (MT[(i+1) % 624] & 0x7fffffffU);
		MT[i] = MT[(i + 397) % 624] ^ (y>>1);
		if ((y % 2) == 1) {
			MT[i] ^= 2567483615U;
		}
	}
}

unsigned int mt_rand(void)
{
	unsigned int y;

	if (index == 0) {
		generateNumbers();
	}

	y = MT[index];
	y ^= y >> 11;
	y ^= (y << 7) & 2636928640U;
	y ^= (y << 15) & 4022730752U;
	y ^= (y >> 18);

	index = (index + 1) % 624;
	return y;
}

unsigned int mt_randint(unsigned int min, unsigned int max)
{
	return min + mt_rand() % (max - min);
}

